# -*- coding:utf-8 -*-
import json


def get_file_data(filename):
    # dic = {}
    content = open(filename, 'r')
    formalTxt = json.load(content)
    return formalTxt


def get_dic_data(dic, li):
    info = 'data'
    for i in li:
        info += '['+i+']'
        if(i.isdigit() and isinstance(dic, list)):
            if(len(dic) >= int(i)):
                dic = dic[int(i)]
            else:
                info += u"does not exist this key"
                return ''
        else:
            if not isinstance(dic, dict):
                info += u"does not exist this key"
                return ''
            if i in dic.has_key:
                dic = dic[i]
            else:
                info += u"does not exist this key"
                return ''
    return dic


def dictationalize_data(self):
    data = get_file_data('data/setup_cache/' + self.host_ip)
    dicData = {}
    dicData["bk_os_type"] = get_dic_data(data, ['ansible_facts', 'ansible_system'])

    if(cmp(dicData.get("bk_os_type", ""), 'Linux') == 0):
        dicData["bk_cpu"] = get_dic_data(data, ['ansible_facts', 'ansible_processor_cores'])*get_dic_data(data, ['ansible_facts', 'ansible_processor_count'])
        dicData["bk_mem"] = get_dic_data(data, ['ansible_facts', 'ansible_memtotal_mb'])
        dicData["platform"] = get_dic_data(data, ['ansible_facts', 'ansible_product_name'])
    elif(cmp(dicData.get("bk_os_type", ""), 'HP-UX') == 0):
        data2 = get_file_data('data/setup_cache/' + self.host_ip)
        dicData["bk_cpu"] = get_dic_data(data2, ['hpux_processor'])
        dicData["bk_mem"] = get_dic_data(data2, ['hpux_mem'])
        dicData["platform"] = get_dic_data(data2, ['ansible_facts', 'ansible_virtualization_role'])
    else:
        raise Exception("cannot tell the OS, update failed: %s" % self.host_ip)
    dicData["bk_os_name"] = get_dic_data(data, ['ansible_facts', 'ansible_distribution'])
    dicData["bk_os_version"] = get_dic_data(data, ['ansible_facts', 'ansible_distribution_version'])
    dicData["bk_cpu_module"] = get_dic_data(data, ['ansible_facts', 'ansible_processor', '2'])
    dicData["bk_mem"] = get_dic_data(data, ['ansible_facts', 'ansible_memtotal_mb'])
    dicData["bk_mac"] = get_dic_data(data, ['ansible_facts', 'ansible_default_ipv4', 'macaddress'])
    dicData["platform"] = get_dic_data(data, ['ansible_facts', 'ansible_product_name'])
    return dicData


def filter_data():
    return None
